import { Injectable } from '@nestjs/common';
import { CreateOrderDto } from 'src/dto/create-order.dto';
import { UpdateOrderDto } from 'src/dto/update-order.dto';
import { Order } from 'src/entity/order.entity';
import { QueryOrderDto } from 'src/dto/query-order.dto';
import { parseQueryParams } from 'src/common/utils';

@Injectable()
export class OrderService {
  create(createOrderDto: CreateOrderDto) {
    return Order.save({
      ...createOrderDto,
    });
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Order.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });

    return { list, count };
  }

  async query(query: QueryOrderDto) {
    let qeryBuilder = Order.createQueryBuilder('order');

    let { queryClone, pageNum, pageSize } = parseQueryParams(query, [
    //  'categoryId',
    ]);

    qeryBuilder.where(queryClone);

    // 关联查询
    // if (query.categoryId) {
    //  qeryBuilder
    //    .leftJoinAndSelect('order.category', 'category')
    //    .andWhere('category.id = :categoryId', {
    //      categoryId: query.categoryId,
    //    });
    // }

    qeryBuilder.skip((pageNum - 1) * pageSize);
    qeryBuilder.take(pageSize);

    let [list, count] = await qeryBuilder.getManyAndCount();

    return { list, count };
  }

  findOne(id: number) {
    return Order.findOneBy({ id });
  }

  update(id: number, updateOrderDto: UpdateOrderDto) {
    return Order.update(id, { ...updateOrderDto });
  }

  remove(id: number) {
    return Order.update(id, { deleteTime: new Date() });
  }
}
